<template>
  <el-form v-loading="loading" label-width="100px">
    <el-form-item label="SPU名称">
      <el-input
        class="spuForm_Form-input"
        v-model="SpuParams.spuName"
        placeholder="请你输入SPU名称"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU品牌">
      <el-select v-model="SpuParams.tmId">
        <el-option
          v-for="item in allTradeMarkData"
          :label="item.tmName"
          :key="item.id"
          :value="item.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input
        v-model="SpuParams.description"
        type="textarea"
        placeholder="请你输入SPU描述"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU图片">
      <!-- 
                v-model:file-list: 展示默认图片 
                action:上次图片的接口
                list-type:文件列表类型
            -->
      <el-upload
        v-model:file-list="imgList"
        action="/api/admin/product/fileUpload"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :before-upload="beforeAvatarUpload"
      >
        <el-icon>
          <Plus />
        </el-icon>
      </el-upload>
      <el-dialog v-model="dialogVisible">
        <img
          style="width: 100%"
          w-full
          :src="dialogImageUrl"
          alt="Preview Image"
        />
      </el-dialog>
    </el-form-item>
    <el-form-item label="SPU销售属性">
      <!-- 展示销售属性的下拉菜单 -->
      <el-select
        v-model="saleAttrIdAndValueName"
        :placeholder="
          unSelectSaleAttr.length
            ? `还未选择${unSelectSaleAttr.length}个`
            : '无未选择'
        "
      >
        <el-option
          :value="`${item.id}:${item.name}`"
          v-for="item in unSelectSaleAttr"
          :label="item.name"
          :key="item.id"
        ></el-option>
      </el-select>
      <el-button
        @click="addSaleAttr"
        :disabled="!saleAttrIdAndValueName"
        type="primary"
        icon="plus"
        style="margin-left: 12px"
      >
        添加属性值
      </el-button>
      <!-- table展示销售属性与属性值的地方 -->
      <el-table
        class="spuForm_table spuForm_table-marginRight"
        :border="true"
        :data="saleAttr"
      >
        <el-table-column
          type="index"
          label="序号"
          align="center"
          width="80"
        ></el-table-column>
        <el-table-column
          prop="saleAttrName"
          label="属性名"
          align="center"
          width="120"
        ></el-table-column>
        <el-table-column label="属性值">
          <template #="{ row, $index }">
            <el-tag
              @close="row.spuSaleAttrValueList.splice($index, 1)"
              v-for="item in row.spuSaleAttrValueList"
              type="success"
              :key="item.id"
              closable
              style="margin: 2px 5px"
            >
              {{ item.saleAttrValueName }}
            </el-tag>
            <el-input
              @blur="toLook(row)"
              v-model="row.saleAttrValue"
              v-if="row.flag"
              placeholder="请输入属性值"
              size="small"
              style="width: 100px"
            ></el-input>
            <el-button
              @click="toEdit(row)"
              v-else
              type="primary"
              size="small"
              icon="Plus"
            ></el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100">
          <template #="{ $index }">
            <el-button
              @click="saleAttr.splice($index, 1)"
              type="danger"
              size="small"
              icon="Delete"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button
        :disabled="saleAttr?.length > 0 ? false : true"
        @click="save"
        type="primary"
      >
        保存
      </el-button>
      <el-button @click="cancel" type="danger">取消</el-button>
    </el-form-item>
  </el-form>
</template>
<script setup lang="ts">
import { ref, computed } from "vue";
import { ElMessage, type UploadProps } from "element-plus";
import type {
  SaleAttrValue,
  HasSaleAttr,
  SaleAttr,
  SpuHasImg,
  Trademark,
  SpuData,
  AllTradeMark,
  SpuImg,
  SaleAttrResponseData,
  HasSaleAttrResponseData,
} from "@/api/product/spu/type";
import {
  reqAddOrUpdateSpu,
  reqAllTradeMark,
  reqSpuImageList,
  reqSpuHasSaleAttr,
  reqAllSaleAttr,
} from "@/api/product/spu";
let $emit = defineEmits(["changeSight"]);
// 存储已有的SPU这些数据
let allTradeMarkData = ref<Trademark[]>([]);
// 商品图片
let imgList = ref<SpuImg[]>([]);
// 已有的SPU销售属性
let saleAttr = ref<SaleAttr[]>([]);
// 全部的销售属性
let allSaleAttrData = ref<HasSaleAttr[]>([]);
// 控制对话框的隐藏与显示效果
let dialogVisible = ref<boolean>(false);
// 存储预览图片的地址
let dialogImageUrl = ref<string>("");
// 判断数据是否全部请求完毕
let loading = ref<boolean>(false);
// 存储已有的SPU对象
let SpuParams = ref<SpuData>({
  category3Id: "", // 收集三级分类的ID
  spuName: "", // SPU的名字
  description: "", // SPU的描述
  tmId: "", // 品牌的ID
  spuImageList: [],
  spuSaleAttrList: [],
});
// 将来收集还未选择的销售属性的ID与属性值名字
let saleAttrIdAndValueName = ref<string>("");
// 点击取消按钮:通知父组件切换场景为1,展示有的SPU的数据
const cancel = (id: number | undefined) => {
  $emit("changeSight", 0, true, id ? true : false);
};

const initHasSpuData = async (spu: SpuData) => {
  loading.value = await true;
  // 存储已有的SPU对象
  SpuParams.value = spu;
  // 获取全部品牌的数据
  let allTradeMark: AllTradeMark = await reqAllTradeMark();
  // 获取某一个品牌旗下全部售卖商品的图片
  let spuImageList: SpuHasImg = await reqSpuImageList(spu.id as number);
  // 获取已有的SPU销售属性的数据
  let spuHasSaleAttr: SaleAttrResponseData = await reqSpuHasSaleAttr(
    spu.id as number,
  );
  // 获取整个项目全部SPU的销售属性
  let allSaleAttr: HasSaleAttrResponseData = await reqAllSaleAttr();

  // 存储全部品牌的数据
  allTradeMarkData.value = allTradeMark.data;
  //SPU对应商品图片
  imgList.value = spuImageList.data.map((item) => {
    return {
      name: item.imgName,
      url: item.imgUrl,
    };
  });
  //存储已有的SPU的销售属性
  saleAttr.value = spuHasSaleAttr.data;
  //存储全部的销售属性
  allSaleAttrData.value = allSaleAttr.data;

  loading.value = await false;
};
// 照片墙点击预览按钮的时候触发的构子
const handlePictureCardPreview = (file: any) => {
  dialogVisible.value = true;
  dialogImageUrl.value = file.url;
};
// 照片墙删除文件的构子
const handleRemove = () => {
  ElMessage({
    type: "success",
    message: "删除成功",
  });
};
// 上传图片之前做什么事
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (
    rawFile.type === "image/png" ||
    rawFile.type === "image/jpeg" ||
    rawFile.type === "image/gif"
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true;
    } else {
      ElMessage({
        type: "error",
        message: "文件上大小必须小于4M",
      });
      return false;
    }
  } else {
    ElMessage({
      type: "error",
      message: "文件上传格式必须是PNG、JPEG、GIF",
    });
    return false;
  }
};
// 计算出当前SPU还未拥有的销售属性
let unSelectSaleAttr = computed(() => {
  let unSelectArr = allSaleAttrData.value.filter((item) => {
    return saleAttr.value.every((data) => {
      return item.name != data.saleAttrName;
    });
  });

  return unSelectArr;
});
// 添加销售属性的方法
const addSaleAttr = () => {
  let [baseSaleAttrId, saleAttrName] = saleAttrIdAndValueName.value.split(":");
  // 准备一个新的销售属性对象，将来带给服务器即可
  let newSaleAttr: SaleAttr = {
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: [],
  };
  // 追加到数组当中
  saleAttr.value.push(newSaleAttr);
  // 清空收集的数据
  saleAttrIdAndValueName.value = "";
};
// 属性值按钮的点击事件
const toEdit = (row: SaleAttr) => {
  row.flag = true;
  row.saleAttrValue = "";
};
// 表单元素失去焦点的事件回调
const toLook = (row: SaleAttr) => {
  // 整理收集的属性的ID与属性值的名字
  const { baseSaleAttrId, saleAttrValue } = row;
  let newSaleAttrValue: SaleAttrValue = {
    baseSaleAttrId,
    saleAttrValueName: saleAttrValue as string,
  };
  // 非法情况判断
  if ((saleAttrValue as string).trim() === "") {
    ElMessage({
      type: "error",
      message: "属性值不能为空",
    });
    return;
  }
  // 判断属性值是否在数组当中存在
  let repeat = row.spuSaleAttrValueList.find((item) => {
    return item.saleAttrValueName === saleAttrValue;
  });
  if (repeat) {
    ElMessage({
      type: "error",
      message: "属性值不能重复",
    });
    return;
  }
  // 追加新的属性值对象
  row.spuSaleAttrValueList.push(newSaleAttrValue);
  // 切换为查看模式
  row.flag = false;
};

// 保存按钮的回调
const save = async () => {
  // 整理参数
  // 1.照片墙的数据
  SpuParams.value.spuImageList = imgList.value.map((item: any) => {
    return {
      imgName: item.name,
      imgUrl: (item.response && item.response.data) || item.url,
    };
  });
  // 2.整理销售属性的数据
  SpuParams.value.spuSaleAttrList = saleAttr.value;
  // 发请求:添加或者更新SPU
  let result: any = await reqAddOrUpdateSpu(SpuParams.value);
  if (result.code === 200) {
    ElMessage({
      type: "success",
      message: SpuParams.value.id ? "更新成功" : "添加成功",
    });
    // 通知父组件切换场景为0
    cancel(SpuParams.value.id);
  } else {
    ElMessage({
      type: "error",
      message: SpuParams.value.id ? "更新失败" : "添加失败",
    });
  }
};

// 添加一个新的SPU初始化请求方法
const initAddSpu = async (c3Id: number | string) => {
  loading.value = true;
  // 清空数据
  Object.assign(SpuParams.value, {
    category3Id: "", // 收集三级分类的ID
    spuName: "", // SPU的名字
    description: "", // SPU的描述
    tmId: "", // 品牌的ID
    spuImageList: [],
    spuSaleAttrList: [],
    id: "",
  });
  // 清空照片
  imgList.value = [];
  // 清空销售属性
  saleAttr.value = [];
  saleAttrIdAndValueName.value = "";
  // 存储三级分类的ID
  SpuParams.value.category3Id = c3Id;
  // 获取全部品牌的数据
  let allTradeMark: AllTradeMark = await reqAllTradeMark();
  // 获取整个项目全部SPU的销售属性
  let allSaleAttr: HasSaleAttrResponseData = await reqAllSaleAttr();
  // 存储数据
  allTradeMarkData.value = allTradeMark.data;
  allSaleAttrData.value = allSaleAttr.data;

  loading.value = false;
};

// 对外暴露
defineExpose({ initHasSpuData, initAddSpu });
</script>
<style scoped lang="scss">
.spuForm_table {
  margin: 16px 0;
}

.spuForm_table-marginRight {
  margin-right: 400px;
}

.spuForm_Form-input {
  width: 199px;
}

@media (max-width: 1280px) {
  .spuForm_table-marginRight {
    margin-right: 100px;
  }
}

@media (max-width: 765px) {
  .spuForm_table-marginRight {
    margin-right: 0;
  }

  .spuForm_Form-input {
    width: 100%;
  }
}
</style>
